{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# High-level Gluon Example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import sys\n",
    "import numpy as np\n",
    "import math\n",
    "import mxnet as mx\n",
    "from mxnet import nd, autograd\n",
    "from mxnet import gluon\n",
    "from common.params import *\n",
    "from common.utils import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "ctx = mx.gpu()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OS:  linux\n",
      "Python:  3.5.2 |Anaconda custom (64-bit)| (default, Jul  2 2016, 17:53:06) \n",
      "[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]\n",
      "MXNet:  0.12.1\n",
      "Numpy:  1.13.3\n",
      "GPU:  ['Tesla K80']\n"
     ]
    }
   ],
   "source": [
    "print(\"OS: \", sys.platform)\n",
    "print(\"Python: \", sys.version)\n",
    "print(\"MXNet: \", mx.__version__)\n",
    "print(\"Numpy: \", np.__version__)\n",
    "print(\"GPU: \", get_gpu_name())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def SymbolModule():\n",
    "    sym = gluon.nn.Sequential()\n",
    "    with sym.name_scope():\n",
    "        sym.add(gluon.nn.Conv2D(channels=50, kernel_size=3, padding=1, activation='relu'))\n",
    "        sym.add(gluon.nn.Conv2D(channels=50, kernel_size=3, padding=1))\n",
    "        sym.add(gluon.nn.MaxPool2D(pool_size=2, strides=2))\n",
    "        sym.add(gluon.nn.Activation('relu'))\n",
    "        # Equiv to gluon.nn.LeakyReLU(0)\n",
    "        sym.add(gluon.nn.Dropout(0.25))\n",
    "        sym.add(gluon.nn.Conv2D(channels=100, kernel_size=3, padding=1, activation='relu'))\n",
    "        sym.add(gluon.nn.Conv2D(channels=100, kernel_size=3, padding=1))\n",
    "        sym.add(gluon.nn.MaxPool2D(pool_size=2, strides=2))\n",
    "        sym.add(gluon.nn.Activation('relu'))\n",
    "        sym.add(gluon.nn.Dropout(0.25))\n",
    "        sym.add(gluon.nn.Flatten())\n",
    "        sym.add(gluon.nn.Dense(512, activation='relu'))\n",
    "        sym.add(gluon.nn.Dropout(0.25))\n",
    "        sym.add(gluon.nn.Dense(N_CLASSES))\n",
    "    return sym"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "def init_model(m):\n",
    "    trainer = gluon.Trainer(m.collect_params(), 'sgd',\n",
    "                            {'learning_rate': LR, 'momentum':MOMENTUM})\n",
    "    criterion = gluon.loss.SoftmaxCrossEntropyLoss()\n",
    "    return trainer, criterion"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preparing train set...\n",
      "Preparing test set...\n",
      "(50000, 3, 32, 32) (10000, 3, 32, 32) (50000,) (10000,)\n",
      "float32 float32 int32 int32\n",
      "CPU times: user 838 ms, sys: 532 ms, total: 1.37 s\n",
      "Wall time: 1.37 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "# Data into format for library\n",
    "x_train, x_test, y_train, y_test = cifar_for_library(channel_first=True)\n",
    "\n",
    "print(x_train.shape, x_test.shape, y_train.shape, y_test.shape)\n",
    "print(x_train.dtype, x_test.dtype, y_train.dtype, y_test.dtype)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 541 ms, sys: 404 ms, total: 945 ms\n",
      "Wall time: 973 ms\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "sym = SymbolModule()\n",
    "sym.collect_params().initialize(mx.init.Xavier(magnitude=2.24), ctx=ctx)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 214 µs, sys: 109 µs, total: 323 µs\n",
      "Wall time: 265 µs\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "trainer, criterion = init_model(sym)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch   0: loss: 1.8297\n",
      "Epoch   1: loss: 1.3560\n",
      "Epoch   2: loss: 1.1277\n",
      "Epoch   3: loss: 0.9620\n",
      "Epoch   4: loss: 0.8325\n",
      "Epoch   5: loss: 0.7242\n",
      "Epoch   6: loss: 0.6293\n",
      "Epoch   7: loss: 0.5441\n",
      "Epoch   8: loss: 0.4776\n",
      "Epoch   9: loss: 0.4079\n",
      "CPU times: user 2min 42s, sys: 28.3 s, total: 3min 11s\n",
      "Wall time: 2min 32s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "# 152s\n",
    "# Sets training = True \n",
    "for j in range(EPOCHS):\n",
    "    train_loss = 0.0\n",
    "    for data, target in yield_mb(x_train, y_train, BATCHSIZE, shuffle=True):\n",
    "        # Get samples\n",
    "        data = nd.array(data).as_in_context(ctx)\n",
    "        target = nd.array(target).as_in_context(ctx)\n",
    "        with autograd.record():\n",
    "            # Forwards\n",
    "            output = sym(data)\n",
    "            # Loss\n",
    "            loss = criterion(output, target)\n",
    "        # Back-prop\n",
    "        loss.backward()\n",
    "        trainer.step(data.shape[0])\n",
    "        train_loss += nd.sum(loss).asscalar()\n",
    "    # Log\n",
    "    print('Epoch %3d: loss: %5.4f'%(j, train_loss/len(x_train)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 1.1 s, sys: 185 ms, total: 1.29 s\n",
      "Wall time: 1.07 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "# Test model\n",
    "n_samples = (y_test.shape[0]//BATCHSIZE)*BATCHSIZE\n",
    "y_guess = np.zeros(n_samples, dtype=np.int)\n",
    "y_truth = y_test[:n_samples]\n",
    "c = 0\n",
    "for data, target in yield_mb(x_test, y_test, BATCHSIZE):\n",
    "    # Get samples\n",
    "    data = nd.array(data).as_in_context(ctx)\n",
    "    # Forwards\n",
    "    output = sym(data)\n",
    "    pred = nd.argmax(output, axis=1)\n",
    "    # Collect results\n",
    "    y_guess[c*BATCHSIZE:(c+1)*BATCHSIZE] = pred.asnumpy()\n",
    "    c += 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Accuracy:  0.759415064103\n"
     ]
    }
   ],
   "source": [
    "print(\"Accuracy: \", sum(y_guess == y_truth)/len(y_guess))"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python [default]",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
